package com.ming.closeto.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ming.closeto.R;
import com.ming.closeto.adapter.SpecialAdapter;
import com.ming.closeto.base.BaseActivity;
import com.ming.closeto.bean.SpecialBean;
import com.ming.closeto.entity.Constant;
import com.ming.closeto.model.CategoryModel;
import com.ming.closeto.utils.LogUtils;
import com.ming.closeto.utils.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 分类
 */
public class CategoryActivity extends BaseActivity {

    private LinearLayout mLoadingLayout;
    private RecyclerView mRecyclerView;
    private GridLayoutManager gridLayoutManager;

    // 复用轮播图详情的 Adapter
    private SpecialAdapter mSpecialAdapter;
    private List<SpecialBean> mList = new ArrayList<>();
    private ArrayList<String> mListBig = new ArrayList<>();

    private String url;

    private String linkUrl;
    private int page = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        initView();
    }

    private void initView() {

        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        url = intent.getStringExtra("url");

        if (!TextUtils.isEmpty(name)) {
            getSupportActionBar().setTitle(name);
        }

        mLoadingLayout = (LinearLayout) findViewById(R.id.mLoadingLayout);
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);

        mSpecialAdapter = new SpecialAdapter(this, mList);
        gridLayoutManager = new GridLayoutManager(this, 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.setAdapter(mSpecialAdapter);

        mSpecialAdapter.setOnItemClickListener(new SpecialAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                Intent i = new Intent(CategoryActivity.this, GalleryActivity.class);
                i.putExtra("position", position);
                i.putStringArrayListExtra("bigUrl", mListBig);
                startActivity(i);
            }
        });

        /**
         * 上拉加载
         *
         * 1. 监听mRecyclerView
         * 2. 滑倒底部的时候显示 Loading
         * 3. 并且加载最新数据
         * 4. 添加在尾部
         * 5. 隐藏loading
         */
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (mRecyclerView.getLayoutManager() instanceof GridLayoutManager) {
                        // 获取屏幕可见的item
                        int lastItem = gridLayoutManager.findLastVisibleItemPosition();
                        if (lastItem >= gridLayoutManager.getItemCount() - 1) {
                            mLoadingLayout.setVisibility(View.VISIBLE);
                            loadNextData();
                        }
                    }
                }
            }
        });


        initCategory();
    }

    // 加载最新数据
    private void loadNextData() {
        if (!TextUtils.isEmpty(linkUrl)) {
            page = page +1;
            OkHttpUtils.get(Constant.WALLPAPER_URL_4 + page, new OkHttpUtils.OnOkHttpCallback() {
                @Override
                public void onFailure(IOException e) {

                }

                @Override
                public void onFailure(String msg) {

                }

                @Override
                public void onSuccessful(String json) {
                    if (!TextUtils.isEmpty(json)) {
                        parsingJson(json);
                    }
                    mLoadingLayout.setVisibility(View.GONE);
                }
            });
        }
    }

    // 首次加载数据
    private void initCategory() {
        if (!TextUtils.isEmpty(url)) {
            // 这里本应使用传过来url  但是因为API的变化，  这里只能从新填写一个能获取到 图片List 的url
            OkHttpUtils.get(Constant.WALLPAPER_URL_3, new OkHttpUtils.OnOkHttpCallback() {
                @Override
                public void onFailure(IOException e) {

                }

                @Override
                public void onFailure(String msg) {

                }

                @Override
                public void onSuccessful(String json) {
                    if (!TextUtils.isEmpty(json)) {
                        parsingJson(json);
                    }
                }
            });
        }
    }

    private void parsingJson(String json) {
        //Toast.makeText(this, "jsonL:" + json, Toast.LENGTH_SHORT).show();

        CategoryModel model = new Gson().fromJson(json, CategoryModel.class);
        List<CategoryModel.ResultsBean> list = model.getResults();
        linkUrl = model.getResults().get(0).getUrl();  // 由于数据接口变化，此代码仅表示已经首次获取过数据
        for (int i=0; i<list.size(); i++) {
            CategoryModel.ResultsBean resultsBean = list.get(i);
            SpecialBean bean = new SpecialBean();
            bean.setSmallUrl(resultsBean.getUrl());
            bean.setBigUrl(resultsBean.getUrl());
            bean.setDownloadSize(resultsBean.getDesc());
            mListBig.add(resultsBean.getUrl());
            mList.add(bean);

            LogUtils.i("--------->" + resultsBean.getUrl());
        }
        mSpecialAdapter.notifyDataSetChanged();

    }
}
